package com.sharemarking.application.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.sharemarking.application.wechat.dto.TextMessageDto;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.thoughtworks.xstream.XStream;

public class MessageUtil {
	/**
	 * xml转为map集合
	 * @param request
	 * @return
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		
		try {
			InputStream ins = request.getInputStream();
			try {
				Document doc = reader.read(ins);
				
				Element root = doc.getRootElement();
				
				@SuppressWarnings("unchecked")
				List<Element> list = root.elements();
				
				for (Element e : list) {
					map.put(e.getName(), e.getText());
				}
				ins.close();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return map;
	}
	
	/**
	 * 将文本消息转为XML对象
	 * @return
	 */
	public static String textMessageToXml(TextMessageDto texMessage) {
		XStream xStream = new XStream();
		xStream.alias("xml", texMessage.getClass());
		return xStream.toXML(texMessage);
	}
}
